﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;

public partial class GenerateInvoicePDF : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsCallback)
        {
            if (Request.QueryString.AllKeys.Contains("InvoiceID") && Request.QueryString.AllKeys.Contains("HasHeader"))
            {
                // select appropriate contenttype, while binary transfer it identifies filetype  
                string contentType = string.Empty;
                int intInvoiceID = Convert.ToInt32(Request.QueryString["InvoiceID"]);

                DataTable dsData = new DataTable(), dtinvDetails = new DataTable();
                dsData = getReportData(intInvoiceID, "uspGetInvoice");
                dsData.Rows[0]["FinalInvoiceAmountWord"] = "Rupees " + NumberToText(Convert.ToInt32(dsData.Rows[0]["FinalInvoiceAmount"]), true) + " Only";

                if (Request.QueryString["HasHeader"] != "1" || dsData.Rows[0]["CompanyLetterHeadPath"] == null)
                    dsData.Rows[0]["CompanyLetterHeadPath"] = "";
                else
                    dsData.Rows[0]["CompanyLetterHeadPath"] = new Uri(Server.MapPath("~/" + dsData.Rows[0]["CompanyLetterHeadPath"])).AbsoluteUri;


                if (dsData.Rows[0]["CompanySignaturePath"] == null)
                    dsData.Rows[0]["CompanySignaturePath"] = "";
                else
                    dsData.Rows[0]["CompanySignaturePath"] = new Uri(Server.MapPath("~/" + dsData.Rows[0]["CompanySignaturePath"])).AbsoluteUri;

                dsData.AcceptChanges();
                dtinvDetails = getReportData(intInvoiceID, "uspGetInvoiceDetails");


                string FileName = "File_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".pdf";
                string extension;
                string encoding;
                string mimeType;
                string[] streams;
                Warning[] warnings;

                LocalReport report = new LocalReport();
                report.ReportPath = Server.MapPath("~/Reports/InvoiceRpt.rdlc");
                report.EnableExternalImages = true;
                report.SetParameters(new ReportParameter("ImagePath", dsData.Rows[0]["CompanyLetterHeadPath"].ToString()));
                report.SetParameters(new ReportParameter("ImagePathSignature", dsData.Rows[0]["CompanySignaturePath"].ToString()));

                report.DataSources.Add(new ReportDataSource() { Name = "dsInvoice_InvoiceReport", Value = dsData });
                report.DataSources.Add(new ReportDataSource() { Name = "dsInvoiceDetails_InvoiceReport", Value = dtinvDetails });

                Byte[] mybytes = report.Render("PDF", null,
                                out extension, out encoding,
                                out mimeType, out streams, out warnings); //for exporting to PDF  


                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=Invoice" + ".pdf");
                Response.OutputStream.Write(mybytes, 0, mybytes.Length); // create the file  
                Response.Flush(); // send it to the client to download  
                Response.End();
            }
        }
    }
 
    private DataTable getReportData(int pIntInvoiceID, string strSP)
    {
        DataSet dsData = new DataSet();
        SqlConnection sqlCon = null;
        SqlDataAdapter sqlCmd = null;

        try
        {
            using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["AuditBillConnectionString"].ConnectionString))
            {
                sqlCmd = new SqlDataAdapter(strSP, sqlCon);
                sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
                sqlCmd.SelectCommand.Parameters.Add(new SqlParameter("InvoiceID", pIntInvoiceID));

                sqlCon.Open();
                sqlCmd.Fill(dsData);

                sqlCon.Close();
            }
        }
        catch
        {
            throw;
        }
        return dsData.Tables[0];
    }

    public static string NumberToText(int number, bool useAnd)
    {
        if (number == 0) return "Zero";
        string and = useAnd ? "and " : ""; // deals with using 'and' separator
        if (number == -2147483648) return "Minus Two Hundred " + and + "Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred " + and + "Forty Eight";
        int[] num = new int[4];
        int first = 0;
        int u, h, t;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (number < 0)
        {
            sb.Append("Minus ");
            number = -number;
        }
        string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };
        string[] words1 = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
        string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
        string[] words3 = { "Thousand ", "Lakh ", "Crore " };
        num[0] = number % 1000; // units
        num[1] = number / 1000;
        num[2] = number / 100000;
        num[1] = num[1] - 100 * num[2]; // thousands
        num[3] = number / 10000000; // crores
        num[2] = num[2] - 100 * num[3]; // lakhs
        for (int i = 3; i > 0; i--)
        {
            if (num[i] != 0)
            {
                first = i;
                break;
            }
        }
        for (int i = first; i >= 0; i--)
        {
            if (num[i] == 0) continue;
            u = num[i] % 10; // ones 
            t = num[i] / 10;
            h = num[i] / 100; // hundreds
            t = t - 10 * h; // tens
            if (h > 0) sb.Append(words0[h] + "Hundred ");
            if (u > 0 || t > 0)
            {
                if (h > 0 || i < first) sb.Append(and);
                if (t == 0)
                    sb.Append(words0[u]);
                else if (t == 1)
                    sb.Append(words1[u]);
                else
                    sb.Append(words2[t - 2] + words0[u]);
            }
            if (i != 0) sb.Append(words3[i - 1]);
        }
        string temp = sb.ToString().TrimEnd();
        return temp;
    }

}